/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * 复制到数组中，使用双指针判断。时间复杂度O(n)，空间复杂度O(n)
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
    let arr = []
    while (head) {
        arr.push(head.val)
        head = head.next
    }
    let left = 0,
        right = arr.length - 1,
        flag = true;
    while (left < right) {
        if (arr[left] !== arr[right]) {
            flag = false
            break
        }
        left++
        right--
    }
    return flag;
};


/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @return {boolean}
 */
var isPalindrome = function (head) {
    let fast = head, slow = head;
    while (fast !== null && fast.next !== null) {
        fast = fast.next.next
        slow = slow.next
    }
    // 临时保存反转后的后半部分链表
    let reverseSecond = reverseList(slow),
        slowTemp = reverseSecond,
        headTemp = head,
        flag = true;
    while (slowTemp) {
        if (slowTemp.val !== headTemp.val) {
            flag = false
            break
        }
        slowTemp = slowTemp.next
        headTemp = headTemp.next
    }
    // 还原后半部分链表
    slow = reverseList(reverseSecond);
    return flag
};

const reverseList = (list) => {
    let newHead = null
    while (list) {
        let temp = list.next;
        list.next = newHead;
        newHead = list;
        list = temp
    }
    return newHead
}